package com.notary.aspect;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.notary.constants.Constant;
import com.notary.util.DesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
@ControllerAdvice(basePackages = "com.notary.controller")
@Slf4j
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Value("${office.deskey}")
    private String deskey;
    @Value("${office.desIv}")
    private String desIv;

    @Value("${request.encryption}")
    private int encryption;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        Method method = methodParameter.getMethod();
        String name = method.getDeclaringClass().getName();
        List<String> className = new ArrayList<>();
        className.add("ReceiveDataController");
        if (CollectionUtil.isNotEmpty(className)) {
            for (String str : className) {
                if (name.indexOf(str) > 0) {
                    return false;
                }
            }

        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (encryption != Constant.requestEncryption.YES.getValue()) {
            return body;
        }
        log.info("【接受到的数据】{}", body);
        //加密
        String encode = null;
        try {
            encode = DesUtil.encode(deskey, desIv, JSON.toJSONString(body));
            log.info("加密后的数据,{}", encode);
        } catch (Exception e) {
            log.error("加密出错:{}", e.getMessage());
        }
        return encode;
    }



/*    public static void main(String[] args) {
       String str="com.notary.controller.ContractController";
        System.out.println(str.indexOf("ContractController"));
    }*/
}


